package StudyCode.Concurrent.Bounce;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author lixiaoyao
 */
public class Bounce {

	public static void main(String[] args) {
		JFrame frame = new BounceFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}

class BounceFrame extends JFrame {

	private BallComponent component;
	private static final int STEPS = 1000;
	private static final int DELAY = 3;

	public BounceFrame() {
		setTitle("Bounce");
		this.component = new BallComponent();
		this.add(this.component, BorderLayout.CENTER);
		JPanel buttonPanel = new JPanel();
		addButton(buttonPanel, "Start", new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				addBall();
			}
		});
		addButton(buttonPanel, "Close", new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		this.add(buttonPanel, BorderLayout.SOUTH);
		pack();
	}

	private void addButton(Container container, String title, ActionListener actionListener) {
		JButton button = new JButton(title);
		container.add(button);
		button.addActionListener(actionListener);
	}

	private void addBall() {
		try {
			Ball ball = new Ball();
			this.component.add(ball);

			for (int i = 1; i <= STEPS; i++) {
				ball.move(this.component.getBounds());
				this.component.paint(this.component.getGraphics());
				Thread.sleep(DELAY);
			}
		} catch (InterruptedException ex) {
			// ignore
		}
	}

}
